package com.rc.saas.tenant.controller.hlht;


import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.BaseSearch;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.utils.BeanUtil;
import com.rc.saas.tenant.common.utils.FileHandler;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.component.UploadImg;
import com.rc.saas.tenant.config.UpYunConfig;
import com.rc.saas.tenant.model.hlht.*;
import com.rc.saas.tenant.model.tenant.Tenant;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.search.hlht.HlhtTenantOpenApplySearch;
import com.rc.saas.tenant.service.hlht.*;
import com.rc.saas.tenant.service.tenant.TenantService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.upyun.WebUploader;
import com.rc.saas.tenant.vo.hlht.HlhtTenantVo;
import com.rc.saas.tenant.vo.hlht.HlhtTenantOpenApplyVo;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;


/**
 * @author frog
 * @date 2021/4/23
 */
@Controller
@RequestMapping("/hlhtTenantOpenApply")
public class HlhtTenantOpenApplyController {
    private static Logger logger = LogManager.getLogger(HlhtTenantOpenApplyController.class);

    private static final String TenantFolderTemp = "/{0}";

    @Autowired
    private HlhtTenantOpenApplyService hlhtTenantOpenApplyService;

    @Autowired
    private HlhtOperatorService hlhtOperatorService;

    @Autowired
    private HlhtTenantOpenforService hlhtTenantOpenforService;

    @Autowired
    private UpYunConfig upYunConfig;

    @Autowired
    private UploadImg uploadImg;

    @Autowired
    private TenantService tenantService;

    @Autowired
    private HlhtTenantSettingService hlhtTenantSettingService;

    @Autowired
    private HlhtOperatorSettingService hlhtOperatorSettingService;

    @Autowired
    private HlhtTenantOpenService hlhtTenantOpenService;

    /**
     * 跳转互联互通列表页面
     *
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model) {
        TenantUser user = ShiroUtils.getSessionUser();
        List<HlhtTenantVo> list = hlhtTenantOpenService.listHlhtTenantByTenantCode(user.getTenantCode());
        model.addAttribute("hlhtTenantList", list);
        return "/templates/hlht/hlhtTenantOpenApply";
    }

    /**
     * 返回申请互联互通list数据
     *
     * @return
     */
    @RequestMapping(value = "/listPageHlhtTenantOpenApply", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listPageHlhtTenantOpenApply(HlhtTenantOpenApplySearch hlhtTenantOpenApplySearch) {
        PageInfo<HlhtTenantOpenApplyVo> pageInfo = hlhtTenantOpenApplyService.listPageHlhtTenantOpenApply(hlhtTenantOpenApplySearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 跳转增加申请互联互通页面
     *
     * @return
     */
    @RequestMapping(value = "/addHlhtTenantOpenApply", method = RequestMethod.GET)
    public String addHlhtTenantOpenApply(Model model, BaseSearch baseSearch) {
        Tenant tenant = tenantService.selectByPrimaryKey(baseSearch.getTenantCode());
        List<HlhtTenantVo> hlhtTenantList = hlhtTenantOpenApplyService.listHlhtTenant(baseSearch);
        model.addAttribute("tenant", tenant);
        model.addAttribute("hlhtTenantList", hlhtTenantList);
        return "/templates/hlht/addHlhtTenantOpenApply";
    }

    /**
     * 跳转至"互联互通审核"页面
     *
     * @return
     */
    @RequestMapping(value = "/auditHlhtTenantOpenApply/{openApplyId}", method = RequestMethod.GET)
    public String auditHlhtTenantOpenApply(Model model, @PathVariable("openApplyId") Long openApplyId) {
        if (!BeanUtil.isValid(openApplyId)) {
            logger.error("openApplyId为：" + openApplyId);
            return "";
        }
        HlhtTenantOpenApply hlhtTenantOpenApply = hlhtTenantOpenApplyService.selectByPrimaryKey(openApplyId);
        Tenant tenant = tenantService.selectByPrimaryKey(hlhtTenantOpenApply.getTenantCode());
        HlhtOperator operator = hlhtOperatorService.selectByPrimaryKey(hlhtTenantOpenApply.getHlhtOperatorId());
        Tenant hlhtTenant = tenantService.selectByPrimaryKey(hlhtTenantOpenApply.getHlhtTenantCode());

        model.addAttribute("hlhtTenantOpenApply", hlhtTenantOpenApply);
        model.addAttribute("uploadPath", upYunConfig.getDownloadRoot());
        model.addAttribute("tenant", tenant);
        model.addAttribute("operator", operator);
        model.addAttribute("hlhtTenant", hlhtTenant);
        return "/templates/hlht/auditHlhtTenantOpenApply";
    }

    /**
     * 跳转编辑互联互通运营商页面
     *
     * @return
     */
    @RequestMapping(value = "/editHlhtTenant/{openApplyId}", method = RequestMethod.GET)
    public String editTenant(Model model, @PathVariable("openApplyId") Long openApplyId) {
        HlhtTenantOpenApply hlhtTenantOpenApply = hlhtTenantOpenApplyService.selectByPrimaryKey(openApplyId);
        HlhtTenantSetting hlhtTenantSetting = hlhtTenantSettingService
                .selectByTenantCodeAndHlhtTenantCodeAndHlhtOperatorId(hlhtTenantOpenApply.getTenantCode(),
                        hlhtTenantOpenApply.getHlhtTenantCode(), hlhtTenantOpenApply.getHlhtOperatorId());
        model.addAttribute("hlhtTenant", hlhtTenantSetting);
        return "/templates/hlht/editHlhtTenantSetting";
    }

    /**
     * 审核互联互通
     *
     * @return
     */
    @RequestMapping(value = "/insertTenantAndOperatorAndOpen", method = RequestMethod.POST)
    @ResponseBody
    public TResponse insertTenantAndOperatorAndOpen(HlhtTenantOpenApply audithlhtTenantOpenApply,
                                                    @RequestParam(value = "docfile", required = false) MultipartFile docfile,
                                                    @RequestParam(value = "fileName") String fileName) {
        if (audithlhtTenantOpenApply.getOpenApplyId() == null) {
            return TResponse.FAIL("openApplyId为空");
        }
        if (!BeanUtil.isValid(audithlhtTenantOpenApply.getBeginDate(), audithlhtTenantOpenApply.getEndDate())) {
            return TResponse.FAIL("请填入开始时间或结束时间,刷新后重试");
        }
        if (audithlhtTenantOpenApply.getEndDate().before(audithlhtTenantOpenApply.getBeginDate())) {
            return TResponse.FAIL("结束时间不能早于开始时间");
        }
        HlhtTenantOpenApply exampleApply = hlhtTenantOpenApplyService.selectByPrimaryKey(audithlhtTenantOpenApply.getOpenApplyId());
        if (exampleApply.getStatus().equals("1")) {
            return TResponse.FAIL("已通过审核的申请不能再次提交");
        }
        if (docfile.getSize() != 0) {
            TResponse tResponse = uploadImg(exampleApply.getOpenApplyId().toString(), fileName, docfile);
            if (tResponse.getStatus() == 200) {
                exampleApply.setContractFile((String) tResponse.getData());
                hlhtTenantOpenApplyService.updateByPrimaryKeySelective(exampleApply);
            } else {
                return tResponse;
            }
        }
        hlhtTenantOpenApplyService.updateByPrimaryKeySelective(audithlhtTenantOpenApply);
        if (audithlhtTenantOpenApply.getStatus().equals("1")) {
            exampleApply.setStatus(audithlhtTenantOpenApply.getStatus());
            hlhtTenantOpenApplyService.addTenantAndOperatorAndOpen(exampleApply);
        }
        return TResponse.SUCCESS();
    }

    /**
     * 保存/编辑申请互联互通信息
     *
     * @return
     */
    @RequestMapping(value = "/saveOrUpdateHlhtTenantOpenApply", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveOrUpdateHlhtTenantOpenApply(HlhtTenantOpenApply hlhtTenantOpenApply,
                                                     @RequestParam(value = "file1", required = false) MultipartFile file1,
                                                     @RequestParam(value = "file2", required = false) MultipartFile file2,
                                                     @RequestParam(value = "file3", required = false) MultipartFile file3,
                                                     @RequestParam(value = "file4", required = false) MultipartFile file4,
                                                     @RequestParam(value = "file5", required = false) MultipartFile file5,
                                                     @RequestParam(value = "docfile", required = false) MultipartFile docfile,
                                                     @RequestParam(value = "fileName") String fileName) {
        try {
            if (!BeanUtil.isValid(hlhtTenantOpenApply.getTenantCode())) {
                logger.error("tenantCode：" + hlhtTenantOpenApply.getTenantCode());
                return TResponse.FAIL("提交失败，tenantCode不能为空");
            }
            if (!BeanUtil.isValid(hlhtTenantOpenApply.getBeginDate(), hlhtTenantOpenApply.getEndDate())) {
                return TResponse.FAIL("请填入开始时间或结束时间,刷新后重试");
            }
            if (hlhtTenantOpenApply.getEndDate().before(hlhtTenantOpenApply.getBeginDate())) {
                return TResponse.FAIL("结束时间不能早于开始时间,刷新后重试");
            }
            List<HlhtTenantOpen> list = new ArrayList<>();

            //存在HlhtOperatorId里的是可以指任何的互联运营商，不分政商
            String code = hlhtTenantOpenApply.getHlhtOperatorId();
            hlhtTenantOpenApply.setHlhtOperatorId(null);
            Tenant tenant = tenantService.selectByPrimaryKey(code);

            //判断code所值向的运营商所属哪个政商
            if (tenant != null) {
                hlhtTenantOpenApply.setHlhtTenantCode(code);
                hlhtTenantOpenApply.setHlhtOpenType("0");
            } else {
                HlhtOperator operator = hlhtOperatorService.selectByPrimaryKey(code);
                hlhtTenantOpenApply.setHlhtOperatorId(code);
                //在第三平台中，若查找出来的运营商属于商业运营商，则apply为商业互联，否则为政务互联
                if (operator.getOperatorType().equals("0")) {
                    hlhtTenantOpenApply.setHlhtOpenType("1");
                } else {
                    hlhtTenantOpenApply.setHlhtOpenType("2");
                }
            }
            hlhtTenantOpenApply.setPayTenantCode("0");
            hlhtTenantOpenApply.setSettleType("1");
            if (docfile.getSize() != 0) {
                TResponse tResponse = uploadImg(hlhtTenantOpenApply.getTenantCode(), fileName, docfile);
                if (tResponse.getStatus() == 200) {
                    hlhtTenantOpenApply.setContractFile((String) tResponse.getData());
                } else {
                    return tResponse;
                }
            }

            //如果是反向互联，需要判断是否saas运营商开放给第三方了
            if ("0".equals(hlhtTenantOpenApply.getHlhtType())) {
                HlhtTenantOpenfor hlhtTenantOpenfor = hlhtTenantOpenforService.listByHlhtOperatorId(hlhtTenantOpenApply.getTenantCode(), code);
                if (hlhtTenantOpenfor != null) {
                    return TResponse.FAIL("该互联用户已经通过瑞晨互联,不能重复互联");
                }
            }


            if (BeanUtil.isValid(hlhtTenantOpenApply.getOpenApplyId())) {
                hlhtTenantOpenApplyService.updateByPrimaryKeySelective(hlhtTenantOpenApply);
            } else {
                //判断该互联关系是否已存在于hlht_tenant_open中
                if ("0".equals(hlhtTenantOpenApply.getHlhtOpenType())) {
                    HlhtTenantOpenExample hlhtTenantOpenExample = new HlhtTenantOpenExample();
                    hlhtTenantOpenExample.createCriteria().andTenantCodeEqualTo(hlhtTenantOpenApply.getTenantCode()).andHlhtTenantCodeEqualTo(hlhtTenantOpenApply.getHlhtTenantCode()).andHlhtTypeEqualTo(hlhtTenantOpenApply.getHlhtType());
                    list = hlhtTenantOpenService.selectByExample(hlhtTenantOpenExample);
                } else if ("1".equals(hlhtTenantOpenApply.getHlhtOpenType()) || "2".equals(hlhtTenantOpenApply.getHlhtOpenType())) {
                    HlhtTenantOpenExample hlhtTenantOpenExample = new HlhtTenantOpenExample();
                    hlhtTenantOpenExample.createCriteria().andTenantCodeEqualTo(hlhtTenantOpenApply.getTenantCode()).andHlhtOperatorIdEqualTo(hlhtTenantOpenApply.getHlhtOperatorId()).andHlhtTypeEqualTo(hlhtTenantOpenApply.getHlhtType());
                    list = hlhtTenantOpenService.selectByExample(hlhtTenantOpenExample);
                }
                if (list.size() > 0) {
                    return TResponse.FAIL("该互联关系已存在");
                }

                if ("0".equals(hlhtTenantOpenApply.getHlhtOpenType()) && "1".equals(hlhtTenantOpenApply.getHlhtType())) {
                    //不能申请内联正向
                    return TResponse.FAIL("请从设备方做内联反向申请");
                }

                hlhtTenantOpenApplyService.insertSelective(hlhtTenantOpenApply);
            }
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("保存运营商互联失败", e);
            return TResponse.FAIL("操作失败");
        }
    }

    /**
     * 更新运营商信息(反向)
     *
     * @param hlhtTenantSetting
     * @return
     */
    @RequestMapping(value = "/updateHlhtTenantSetting", method = RequestMethod.POST)
    @ResponseBody
    public TResponse updateTenant(HlhtTenantSetting hlhtTenantSetting) {
        try {
            if (hlhtTenantSetting.getHlhtTenantSettingId() == null) {
                return TResponse.FAIL("更新失败，id为" + hlhtTenantSetting.getHlhtTenantSettingId());
            }
            hlhtTenantSettingService.updateByPrimaryKeySelective(hlhtTenantSetting);
        } catch (Exception e) {
            logger.error("更新失败", e);
            TResponse.FAIL("更新失败");
        }
        return TResponse.SUCCESS("更新成功");
    }

    /**
     * 跳转编辑互联互通运营商页面（正向）
     */
    @RequestMapping(value = "/editHlhtOperator/{openApplyId}", method = RequestMethod.GET)
    public String editOperator(Model model, @PathVariable("openApplyId") Long openApplyId) {
        HlhtTenantOpenApply hlhtTenantOpenApply = hlhtTenantOpenApplyService.selectByPrimaryKey(openApplyId);
        HlhtOperatorSetting hlhtOperatorSetting = hlhtOperatorSettingService
                .selectByTenantCodeAndHlhtOperatorId(hlhtTenantOpenApply.getTenantCode(), hlhtTenantOpenApply.getHlhtOperatorId());
        model.addAttribute("hlhtOperator", hlhtOperatorSetting);
        return "/templates/hlht/editHlhtOperatorSetting";
    }

    /**
     * 更新运营商信息(正向)
     *
     * @return
     */
    @RequestMapping(value = "/updateHlhtOperatorSetting", method = RequestMethod.POST)
    @ResponseBody
    public TResponse updateOperator(HlhtOperatorSetting hlhtOperatorSetting) {
        try {
            if (hlhtOperatorSetting.getHlhtOperatorSettingId() == null) {
                return TResponse.FAIL("更新失败，id为" + hlhtOperatorSetting.getHlhtOperatorSettingId());
            }
            hlhtOperatorSettingService.updateByPrimaryKeySelective(hlhtOperatorSetting);
        } catch (Exception e) {
            logger.error("更新失败", e);
            return TResponse.FAIL("更新失败");
        }
        return TResponse.SUCCESS("更新成功");
    }

    /**
     * 删除申请互联互通信息
     *
     * @return
     */
    @RequestMapping(value = "/deleteHlhtTenantOpenApply", method = RequestMethod.POST)
    @ResponseBody
    public TResponse deleteHlhtTenantOpenApply(Long tenantCode) {
        try {
            hlhtTenantOpenApplyService.deleteByPrimaryKey(tenantCode);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("删除运营商互联", e);
            return TResponse.FAIL("操作失败");
        }
    }

    /**
     * 上传图片
     *
     * @param uploadFile
     * @return
     */
    private TResponse uploadImg(String tenantCode, String fileName, MultipartFile uploadFile) {
        if (uploadFile == null) {
            return TResponse.FAIL("file不存在");
        }
        WebUploader webUploader = WebUploader.getInstance(upYunConfig);
        String uploadFileName = null;
        try {
            uploadFileName = uploadFile(tenantCode, fileName, webUploader, uploadFile);
        } catch (Exception e) {
            e.printStackTrace();
            return TResponse.FAIL("操作失败");
        }
        if (StringUtils.isBlank(uploadFileName)) {
            return TResponse.FAIL("操作失败");
        }
        TResponse success = TResponse.SUCCESS();
        success.put(uploadFileName);
        return success;
    }

    /**
     * 上传到CDN，并返回存储的路径
     *
     * @param webUploader
     * @param file
     * @return
     * @throws NoSuchAlgorithmException
     * @throws SignatureException
     * @throws InvalidKeyException
     */
    private String uploadFile(String tenantCode, String fileName, WebUploader webUploader, MultipartFile file) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException {
        //CDN存放路径:/运营商编号/文件
        //String uploadFileName = upYunConfig.getUploadImagePath();
        String uploadFileName = MessageFormat.format(TenantFolderTemp, tenantCode) + upYunConfig.getUploadEnterprisePath();
        uploadFileName = uploadFileName + fileName + "-";
        uploadFileName = uploadFileName + FileHandler.createFileNameByTimeRole(file.getOriginalFilename());
        //本地硬盘存放路径
        CommonsMultipartFile cf = (CommonsMultipartFile) file;
        DiskFileItem df = (DiskFileItem) cf.getFileItem();
        File localFile = df.getStoreLocation();

        boolean result = webUploader.uploadFile(uploadFileName, localFile);
        if (result) {
            return uploadFileName;
        } else {
            return null;
        }
    }

}
